package net.baikentools.page.reverseengineering;

import java.io.File;
import java.io.IOException;
import java.io.Serializable;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.xml.bind.JAXBContext;

import net.baikentools.model.ReverseEngineeringResult;
import net.baikentools.util.ConsoleReader;
import net.baikentools.util.JAXBUtil;

import org.primefaces.event.FileUploadEvent;

import com.google.common.io.Files;

@ManagedBean
@ViewScoped
public class ReverseEngineeringCSharp implements Serializable {

	private ReverseEngineeringResult result;

	public ReverseEngineeringCSharp() {
	}

	public void handleFileUpload(FileUploadEvent event) {
		try {
			File fileName = File.createTempFile("staruml", "dll");
			Files.write(event.getFile().getContents(), fileName);

			ConsoleReader consoleReader = new ConsoleReader(
					"staruml-baikentool-csharpreverse.exe \""
							+ fileName + "\" ");

			result = JAXBUtil.read(consoleReader.getOutput());

			System.out.println(fileName);

		} catch (IOException e) {
			e.printStackTrace();
		}

		FacesMessage msg = new FacesMessage("Succesful", event.getFile()
				.getFileName() + " is uploaded.");
		FacesContext.getCurrentInstance().addMessage(null, msg);
	}

	public ReverseEngineeringResult getResult() {
		return result;
	}

	public void setResult(ReverseEngineeringResult result) {
		this.result = result;
	}

}
